<template>
  <div class="create-post-page">
    <h4 class="text-center">{{ isEditMode ? "编辑文章" : "新建文章" }}</h4>
    <UploaderFile
      action="/upload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
      :beforeUpload="uploadedCheck"
      @file-uploaded="handleFileUploaded"
      :uploaded="uploadedData"
    >
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" roule="status">
            <!-- <span class="scr-only">load....</span> -->
          </div>
        </div>
        <h2>正在上传</h2>
      </template>

      <template #uploaded="dataProps">
        <div class="uploaded-area">
          <img :src="dataProps.uploadedData.data.url" alt="" />
          <h3>点击重新上传</h3>
        </div>
      </template>
    </UploaderFile>
    <!-- <input type="file" name="file" @change="handleFileChange" /> -->
    <ValidateForm @form-submit="onFormSubmit">
      <div class="mb-3 mt-3">
        <label for="" class="form-label">文章标题</label>
        <ValidateInpt
          placeholder="请输入文章标题"
          type="text"
          :rules="titleRules"
          v-model="titleVal"
          @value="titleValue"
        >
        </ValidateInpt>
      </div>

      <div class="mb-3">
        <label for="" class="form-label">文章详情</label>
        <textarea ref="textArea"></textarea>
        <ValidateInpt
          placeholder="请输入文章详情"
          rows="10"
          tag="textarea"
          type="text"
          :rules="contentRules"
          v-model="contentVal"
          @value="contentValue"
        >
        </ValidateInpt>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">
          {{ isEditMode ? "更新文章" : "上传文章" }}
        </button>
      </template>
    </ValidateForm>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted, ref } from "vue";
import { useStore } from "vuex";
import {
  GolbalDataProps,
  UserProps,
  ResponseType,
  IamgeProps,
  PostProps,
} from "@/store";
import { useRoute, useRouter } from "vue-router";
import ValidateForm from "@/components/validateForm.vue";
import ValidateInpt, { RulesProp } from "@/components/ValidateInpt.vue";
// import { PostProps } from "@/testData";
import axios from "axios";
import UploaderFile from "./UploaderFile.vue";
import { beforUploadCheck } from "../hooks/helper";
import createMessage from "@/hooks/createMessage";
import EasyMDE from "easymde";

export default defineComponent({
  name: "CreatePost",
  components: {
    ValidateForm,
    UploaderFile,
    ValidateInpt,
  },
  setup() {
    const textArea = ref<null | HTMLTextAreaElement>(null);
    const titleVal = ref("");
    const contentVal = ref("");
    const titleValue = (val: string) => {
      titleVal.value = val;
    };
    const contentValue = (val: string) => {
      contentVal.value = val;
    };
    const router = useRouter();
    const route = useRoute();
    const isEditMode = !!route.query.id;
    const uploadedData = ref();
    const store = useStore<GolbalDataProps>();
    const titleRules: RulesProp = [
      { type: "required", message: "文章标题不能为空" },
    ];
    const contentRules: RulesProp = [
      { type: "required", message: "文章详情不能为空" },
    ];
    let imageId = "";
    const uploadedCheck = (file: File) => {
      const result = beforUploadCheck(file, {
        format: ["image/jpeg", "image/png"],
        size: 1,
      });

      const { passed, error } = result;
      if (error === "format") {
        createMessage("上传图片只能是JPG/PNG格式", "error");
      }
      if (error === "size") {
        createMessage("上传图片大小不能超过1MB", "error");
      }
      return passed;
    };
    const handleFileUploaded = (rawdata: ResponseType<IamgeProps>) => {
      if (rawdata.data._id) {
        imageId = rawdata.data._id;
      }
    };
    onMounted(() => {
      if (textArea.value) {
        const easyMDEInstance = new EasyMDE({ element: textArea.value });
      }
      if (isEditMode) {
        store
          .dispatch("fetchPost", route.query.id)
          .then((rawData: ResponseType<PostProps>) => {
            console.log(rawData);
            const currentPost = rawData.data;
            //如果存在就赋值
            if (currentPost.image) {
              uploadedData.value = { data: currentPost.image };
              console.log(uploadedData.value);
            }
            titleVal.value = currentPost.title;
            contentVal.value = currentPost.content || "";
          });
      }
    });
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const { column, _id } = store.state.user;
        if (column) {
          const newPost: PostProps = {
            // id: new Date().getTime(),
            // _id: "",
            title: titleVal.value,
            content: contentVal.value,
            column,
            // createdAt: new Date().toLocaleString(),
            author: _id,
          };
          if (imageId) {
            newPost.image = imageId;
          }

          const actionName = isEditMode ? "updatePost" : "createPost";
          const sendData = isEditMode
            ? {
                id: route.query.id,
                payload: newPost,
              }
            : newPost;
          //自动跳转到详情页
          store.dispatch(actionName, sendData).then(() => {
            createMessage("发表成功，2秒后跳转到文章", "success");
            router.push({ name: "column", params: { id: column } });
          });
        }
      }
    };
    return {
      titleVal,
      contentVal,
      titleRules,
      contentRules,
      titleValue,
      onFormSubmit,
      textArea,
      contentValue,
      uploadedCheck,
      handleFileUploaded,
      isEditMode,
      uploadedData,
    };
  },
});
</script>

<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}

.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.uploaded-area {
  position: relative;
}
.uploaded-area:hover h3 {
  display: block;
}
.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>
